#! /usr/bin/env python
# MAKE SURE TO pip install distribute --upgrade

import sys, os
sys.path.append(os.getcwd())

from distutils.core import setup
from glob import glob

from setuptools import find_packages
#from setuptools import setup

from distutils.command import build, install, install_lib
from setuptools.command import develop, test, build_ext

VERSION = open('VERSION').read().strip()
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

#XXX unused it seems
forest = os.environ.get('FOREST', None) == "True"

if not on_rtd:
    def gen_data_files():
        results = []#("bin", ["tree-build", 'tree-respin', 'tree-tousb'])]

        BASEDIR = 'share/forest/'
        dirs = ['examples', 'docs']

        for src_dir in dirs:
            for root,dirs,files in os.walk(src_dir):
                results.append((BASEDIR+root, map(lambda f:root + "/" + f, files)))

        return results
else:
    def gen_data_files():
        return []

def do_system(cmd):
    print cmd
    if os.system(cmd):
        raise SystemError("Failed: %s" % cmd)

class new_install(install.install):

    def run(self):
        print "INSTALL"

        install.install.run(self)

class new_build_ext(build_ext.build_ext):
    def run(self):
        # Hack to build C sources first
        #if os.path.exists('c'):
        #    print "Removing old c directory"
        #    shutil.rmtree('c')
        do_system("make -B forest/bin/tree-build")
        #os.utime("c/config.h.in", (time.time(), time.time()))
        #do_system("cd c; ./configure; make")

        build_ext.build_ext.run(self)


class new_develop_ext(develop.develop):
    def run(self):
        print "DEVELOP"
        develop.develop.run(self)
        do_system("sudo chown root:root forest/bin/tree-build")
        do_system("sudo chmod 4755 forest/bin/tree-build")


class new_install_lib(install_lib.install_lib):
    def run(self):
        print "INSTALL_LIB"
        install_lib.install_lib.run(self)

#cmdclass = dict(build_ext = new_build_ext, develop=new_develop_ext, install_lib=new_install_lib)
def main():

    setup(name="forest",
          version=VERSION,
          description="Forest",
          long_description="",
          author="Nate Skulic",
          author_email="nate.skulic@gmail.com",
          url="http://code.google.com/p/treebuilder",
          download_url="http://code.google.com/p/treebuilder/downloads/list",
          license="Apache License (2.0)",
          packages=find_packages(exclude=["tests"]),
          requires=['PyYAML', 'lxml', 'pycurl', 'sqlalchemy'],
          install_requires=['PyYAML'],
          setup_requires=['PyYAML'],
          data_files=gen_data_files(),
          include_package_data = True,
          scripts=[
            #'forest/bin/tree-build',
            'forest/bin/tree-respin',
            'forest/bin/tree-tousb',
            #'forest/bin/tree-install',
            'forest/bin/tree-update'
          ],
          package_dir={'forest': 'forest'},

          # keep the binaries with the package so that that we can embed forest (and its binaries) by copying the site-package
          package_data={'forest': [
            'server/templates/*.html',
            'server/static/*'
          ]},

          classifiers=[
          'Development Status :: 4 - Beta',
          'Environment :: Console',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: Apache Software License',
          ]
          #, cmdclass=cmdclass
          )

if __name__ == '__main__':
    main()
